/**
 * Created by jianglinjie on Mon Oct 09 2017
 * 
 */
'use strict';
/* eslint-disable no-unused-vars*/

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _ServiceError = require('../error/ServiceError');

var _ServiceError2 = _interopRequireDefault(_ServiceError);

var _auth = require('../auth');

var _auth2 = _interopRequireDefault(_auth);

var _ErrorCode = require('../../constants/ErrorCode');

var ErrorCode = _interopRequireWildcard(_ErrorCode);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function isValidBody(body) {
  if (typeof body.succeed === 'boolean' && typeof body.errorCode === 'string' && typeof body.msg === 'string' && _typeof(body.data) === 'object') {
    return true;
  }

  return false;
}

var ServiceNetHandler = function () {
  function ServiceNetHandler() {
    _classCallCheck(this, ServiceNetHandler);
  }

  _createClass(ServiceNetHandler, [{
    key: 'injectExtraURLParam',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(request) {
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt('return', {});

              case 1:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function injectExtraURLParam(_x) {
        return _ref.apply(this, arguments);
      }

      return injectExtraURLParam;
    }()
  }, {
    key: 'injectExtraHeaders',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(request) {
        var token;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return _auth2.default.getToken();

              case 2:
                token = _context2.sent;

                if (!token) {
                  _context2.next = 7;
                  break;
                }

                return _context2.abrupt('return', {
                  Authorization: 'Bearer ' + token
                });

              case 7:
                return _context2.abrupt('return', {});

              case 8:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function injectExtraHeaders(_x2) {
        return _ref2.apply(this, arguments);
      }

      return injectExtraHeaders;
    }()
  }, {
    key: 'verifyResponse',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(response) {
        var body;
        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                body = response.body;

                if (isValidBody(body)) {
                  _context3.next = 3;
                  break;
                }

                return _context3.abrupt('return', {
                  error: new _ServiceError2.default(ErrorCode.RES_BODY_INVALID, 'body格式不合法'),
                  ok: false
                });

              case 3:
                if (!body.succeed) {
                  _context3.next = 7;
                  break;
                }

                return _context3.abrupt('return', {
                  error: null,
                  ok: true
                });

              case 7:
                return _context3.abrupt('return', {
                  error: new _ServiceError2.default(body.errorCode, body.msg),
                  ok: false
                });

              case 8:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function verifyResponse(_x3) {
        return _ref3.apply(this, arguments);
      }

      return verifyResponse;
    }()
  }, {
    key: 'handleError',
    value: function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(error, request) {
        var retry, succeed;
        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                retry = false;
                _context4.prev = 1;

                if (!(0, _ServiceError.isServiceError)(error)) {
                  _context4.next = 13;
                  break;
                }

                if (!(error.errorCode === ErrorCode.TOKEN_EXPIRE)) {
                  _context4.next = 10;
                  break;
                }

                _context4.next = 6;
                return _auth2.default.autoLogin();

              case 6:
                succeed = _context4.sent;

                if (succeed) {
                  //自动登录成功 重试
                  retry = true;
                }
                _context4.next = 13;
                break;

              case 10:
                if (!(error.errorCode === ErrorCode.TOKEN_INVALID)) {
                  _context4.next = 13;
                  break;
                }

                _context4.next = 13;
                return _auth2.default.logout();

              case 13:
                _context4.next = 18;
                break;

              case 15:
                _context4.prev = 15;
                _context4.t0 = _context4['catch'](1);

                retry = false;

              case 18:
                return _context4.abrupt('return', {
                  retry: retry
                });

              case 19:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this, [[1, 15]]);
      }));

      function handleError(_x4, _x5) {
        return _ref4.apply(this, arguments);
      }

      return handleError;
    }()
  }]);

  return ServiceNetHandler;
}();

exports.default = new ServiceNetHandler();